package com.wejoy.video.middle.station.data.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.wejoy.video.middle.station.data.constant.RedisKeys;
import com.wejoy.video.middle.station.data.enums.file.EnumUpload;
import com.wejoy.video.middle.station.data.service.file.IFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * @Description 二维码生成
 * @Date 2021/9/2 17:12
 * @Author admin
 */
@Component
public class QrCodeUtil {

    private static Logger logger = LoggerFactory.getLogger(QrCodeUtil.class);
    /**
     * 二维码宽度
     */
    private final static int WIDTH = 300;
    /**
     * 二维码高度
     */
    private final static int HEIGHT = 300;
    /**
     * 图片格式  如果是png类型，logo图变成黑白的
     */
    private final static String FORMAT = "jpg";
    private static IFileService fileService;

    private final static String LOGO_URL = "https://video.middle.station-image.v2gogo.com/logo/logo.png";

    @Autowired
    public void setFileService(IFileService fileService) {
        QrCodeUtil.fileService = fileService;
    }


    /**
     * @param content 创建二维码
     * @param isLogo  是否生成带logo图片
     */
    @Cacheable(value = RedisKeys.IMAGE_QRCODE, key = "#content + ':isLogo:' + #isLogo ", condition = "#extensionTypeId != null")
    public String createQrCode(String content, boolean isLogo) {
        // 1.定义HashMap hints
        HashMap hints = new HashMap(3);
        // 2.hints调用put函数设置字符集、间距以及纠错度为M
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //纠错等级【L，M，Q，H】
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        // 生成二维码
        try {
            // 图片输出流
            ByteArrayOutputStream qrCodeOutputStream = new ByteArrayOutputStream();
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 3.最后用MultiformatWriter函数类调用echoed函数并返回一个值 然后写入文件
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            // 这里路径后面的img.png不可省略，前面是自己选取生成的图片地址
            MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, qrCodeOutputStream);
            //*************添加logo*****************
            //读取二维码图片
            BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(qrCodeOutputStream.toByteArray()));
            //获取画笔
            Graphics2D graphics = bufferedImage.createGraphics();
            //读取logo图片
            if (isLogo) {
                URL url = new URL("https://video.middle.station-image.v2gogo.com/logo/logo.png");
                //打开链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置请求方式为"GET"
                conn.setRequestMethod("GET");
                //超时响应时间为5秒
                conn.setConnectTimeout(5 * 1000);
                //通过输入流获取图片数据
                InputStream logoInputStream = conn.getInputStream();
//                File file = new File("C:\\Users\\px\\Desktop\\logo.png");
//                BufferedImage logo = ImageIO.read(file);
                BufferedImage logo = ImageIO.read(logoInputStream);
                //设置二维码大小，太大了会覆盖二维码，此处为20%
                int logoWidth = logo.getWidth() > bufferedImage.getWidth() * 2 / 10 ? (bufferedImage.getWidth() * 2 / 10) : logo.getWidth();
                int logoHeight = logo.getHeight() > bufferedImage.getHeight() * 2 / 10 ? (bufferedImage.getHeight() * 2 / 10) : logo.getHeight();
                //设置logo图片放置的位置，中心
                int x = (bufferedImage.getWidth() - logoWidth) / 2;
                int y = (bufferedImage.getHeight() - logoHeight) / 2;
                //开始合并并绘制图片
                graphics.drawImage(logo, x, y, logoWidth, logoHeight, null);
                graphics.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
                //logob边框大小
                graphics.setStroke(new BasicStroke(2));
                //logo边框颜色
                graphics.setColor(Color.WHITE);
                graphics.drawRect(x, y, logoWidth, logoHeight);
                graphics.dispose();
                logo.flush();
                bufferedImage.flush();
                ByteArrayOutputStream logoQrCodeOutputStream = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, FORMAT, logoQrCodeOutputStream);
//                ImageIO.write(bufferedImage, FORMAT ,new File("D:/test1.jpg"));
                // 上传到七牛
                String key = fileService.upload(EnumUpload.QR_CODE, logoQrCodeOutputStream.toByteArray()).getKey();
                return key;
            } else {
                // 上传到七牛
                String key = fileService.upload(EnumUpload.QR_CODE, qrCodeOutputStream.toByteArray()).getKey();
                return key;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("生成二维码错误：{}", e.getMessage());
        }
        return null;
    }

    /**
     * @param content 创建二维码
     * @param isLogo  是否生成带logo图片
     */
    public String createQrCodeNoCache(String content, boolean isLogo) {
        // 1.定义HashMap hints
        HashMap hints = new HashMap(3);
        // 2.hints调用put函数设置字符集、间距以及纠错度为M
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //纠错等级【L，M，Q，H】
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        // 生成二维码
        try {
            // 图片输出流
            ByteArrayOutputStream qrCodeOutputStream = new ByteArrayOutputStream();
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 3.最后用MultiformatWriter函数类调用echoed函数并返回一个值 然后写入文件
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            // 这里路径后面的img.png不可省略，前面是自己选取生成的图片地址
            MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, qrCodeOutputStream);
            //*************添加logo*****************
            //读取二维码图片
            BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(qrCodeOutputStream.toByteArray()));
            //获取画笔
            Graphics2D graphics = bufferedImage.createGraphics();
            //读取logo图片
            if (isLogo) {
                URL url = new URL("https://video.middle.station-image.v2gogo.com/logo/logo.png");
                //打开链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置请求方式为"GET"
                conn.setRequestMethod("GET");
                //超时响应时间为5秒
                conn.setConnectTimeout(5 * 1000);
                //通过输入流获取图片数据
                InputStream logoInputStream = conn.getInputStream();
//                File file = new File("C:\\Users\\px\\Desktop\\logo.png");
//                BufferedImage logo = ImageIO.read(file);
                BufferedImage logo = ImageIO.read(logoInputStream);
                //设置二维码大小，太大了会覆盖二维码，此处为20%
                int logoWidth = logo.getWidth() > bufferedImage.getWidth() * 2 / 10 ? (bufferedImage.getWidth() * 2 / 10) : logo.getWidth();
                int logoHeight = logo.getHeight() > bufferedImage.getHeight() * 2 / 10 ? (bufferedImage.getHeight() * 2 / 10) : logo.getHeight();
                //设置logo图片放置的位置，中心
                int x = (bufferedImage.getWidth() - logoWidth) / 2;
                int y = (bufferedImage.getHeight() - logoHeight) / 2;
                //开始合并并绘制图片
                graphics.drawImage(logo, x, y, logoWidth, logoHeight, null);
                graphics.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
                //logob边框大小
                graphics.setStroke(new BasicStroke(2));
                //logo边框颜色
                graphics.setColor(Color.WHITE);
                graphics.drawRect(x, y, logoWidth, logoHeight);
                graphics.dispose();
                logo.flush();
                bufferedImage.flush();
                ByteArrayOutputStream logoQrCodeOutputStream = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, FORMAT, logoQrCodeOutputStream);
//                ImageIO.write(bufferedImage, FORMAT ,new File("D:/test1.jpg"));
                // 上传到七牛
                String key = fileService.upload(EnumUpload.QR_CODE, logoQrCodeOutputStream.toByteArray()).getKey();
                return key;
            } else {
                // 上传到七牛
                String key = fileService.upload(EnumUpload.QR_CODE, qrCodeOutputStream.toByteArray()).getKey();
                return key;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("生成二维码错误：{}", e.getMessage());
        }
        return null;
    }
}
